<template>
	<div class="meshGeneration b f22">
		<el-row>
			<el-col :span="24">
				<h5 class="">网格划分</h5>
			</el-col>
		</el-row>

		<el-form :inline="true" :model="meshForm" :rules="meshRule" :label-width="100" ref="formRef">
			<el-row>
				<el-col :span="9">
					<el-form-item label="任务名称" prop="taskName" label-position="right" class="w91">
						<el-input maxlength="100"
							maxLength="30"
							v-on:input="meshForm.taskName = meshForm.taskName.replace(/[\u4e00-\u9fa5]/gi, '')"
							v-model="meshForm.taskName" placeholder="请输入任务名称" clearable />
					</el-form-item>
					<!-- </el-form> -->
				</el-col>
				<el-col :span="9">
					<el-form-item label="模型文件" class="w91 pt uploadForm"
						:rules="[{ required: true, message: '请上传模型', trigger: 'blur' }]"
						style="cursor: pointer !important;">
						<el-input style="cursor: pointer !important;" v-model="modelLocalPath" readonly
							placeholder="请选择模型文件" @click="upload" clearable>
							<template #suffix>
								<div @click="upload">
									<plus-btn />
								</div>
							</template>
						</el-input>
					</el-form-item>
					<el-upload class="avatar-uploader" ref="uploadRef" :http-request="uploadRequest"
                            :show-file-list="false">
                        </el-upload>
				</el-col>
				<el-col :span="6">
					<el-button type="primary" class="startbtn mt16" style="margin-left: 80px"
						@click="handleSubmitMeshForm(formRef)">提交网格划分</el-button>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="9">
					<el-form-item label="网络类型" class="w91" prop="elementType">
						<el-select v-model="meshForm.elementType" placeholder="" @change="changeSimulator" clearable
							class="w100">
							<el-option value="Tet" label="Tet" />
							<el-option value="Hex" label="Hex" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="9">
					<el-form-item label="阶次" class="w91" prop="elementOrder">
						<el-select v-model="meshForm.elementOrder" placeholder="Heat Transfer" clearable class="w100">
							<el-option value="1" label="1" />
							<el-option value="2" label="2" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-button style="visibility: hidden" type="primary">Primary</el-button>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="9">
					<el-form-item label="方法" class="w91" prop="method">
						<el-select v-model="meshForm.method" placeholder="" @change="changeSimulator" clearable
							class="w100">
							<el-option value="Delaunay" label="Delaunay" />
							<el-option value="New Delaunay" label="New Delaunay" />
							<el-option value="Frontal" label="Frontal" />
							<el-option value="Frontal Delaunay" label="Frontal Delaunay" />
							<el-option value="Frontal Hex" label="Frontal Hex" />
							<el-option value="MMG3D" label="MMG3D" />
							<el-option value="R-tree" label="R-tree" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="9">
					<el-form-item label="尺寸因子" class="w91" prop="sizeFactor">
						<el-input-number class="w100" v-model="meshForm.sizeFactor" :min="0" :max="1"
							:value-on-clear="1" controls-position="right" size="large" @change="handleChange" />
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-button style="visibility: hidden" type="primary">Primary</el-button>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="9">
					<el-form-item label="最小单元尺寸" class="w91" prop="minSize">
						<el-input-number class="w100" v-model="meshForm.minSize" :min="0" :step="1" :value-on-clear="0"
							controls-position="right" size="large" @change="handleChange" />
					</el-form-item>
				</el-col>
				<el-col :span="9">
					<el-form-item label="最大单元尺寸" class="w91" prop="maxSize">
						<el-input-number class="w100" v-model="meshForm.maxSize" :min="0" :step="1"
							:value-on-clear="100" controls-position="right" size="large" @change="handleChange" />
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-button style="visibility: hidden" type="primary">Primary</el-button>
				</el-col>
			</el-row>
		</el-form>
		<el-row style="margin-top: 30px">
			<el-col :span="24">
				<div>
					<h5 class="">模型显示</h5>
					<div v-loading="modelLoading" element-loading-text="模型加载中..." class="b fx"
						style="border: 1px solid #d0d1d1; padding: 5px; margin-top: 10px; overflow: auto">
						<div>
							<nodeTreeVue ref="nodeTreeVueDom" />
						</div>
						<div id="modelPreview" class="modelBox">
							<canvas id="viewer"></canvas>
						</div>
					</div>
				</div>
				<div></div>
			</el-col>
		</el-row>

	</div>
</template>
<script setup>

import { reactive, ref, onMounted, computed, watch } from 'vue'
import { modelPath, modelLocalPath } from '@/utils/modelPath.js'
import plusBtn from '@/components/plusBtn/Index.vue'
import { fastCaeMesh } from '../api/mesh'
import { ElMessage, ElMessageBox } from 'element-plus'
import { LoaderSettings } from '@/v2/entity/LoaderSettings'
import StpLoader from '@/v2/engine/StpLoader.js'
import { addSubTask, updateFile } from '../api/simulate'

const formRef = ref()
const meshForm = reactive({
	"taskName": '',
	"appId": "4",
	"appModuleId": "0",
	"elementOrder": "1",    //阶次
	"elementType": "Tet",   //网格类型
	"maxSize": "100",       //最大单元尺寸
	"meshPath": "",
	"method": "Delaunay",  //方法
	"minSize": "0",         //最小单元尺寸
	"param": {},
	"sizeFactor": "1",       //尺寸因子
	"stpPath": modelPath.value,      //模型地址
	"subTaskId": "",
	"taskId": "",

})
const meshRule = ref({
	taskName: [
		{
			required: true, message: '请输入任务名称', trigger: 'blur',
		},
	],
	elementOrder: [
		{
			required: true, message: '请选择阶次', trigger: 'blur',
		}],
	elementType: [
		{
			required: true, message: '请选择网格类型', trigger: 'blur',
		},
	],
	maxSize: [
		{
			required: true, message: '请输入最大单元尺寸', trigger: 'blur',
		},
	],
	minSize: [
		{
			required: true, message: '请输入最小单元尺寸', trigger: 'blur',
		},
	],
	stpPath: [
		{
			required: true, message: '请上传模型', trigger: 'blur',
		},
	],
	sizeFactor: [
		{
			required: true, message: '请输入尺寸因子', trigger: 'blur',
		},
	],
	method: [
		{
			required: true, message: '请选择方法', trigger: 'blur',
		},
	],
})
const modelLoading = ref(false)//模型加载状态

let isUpload = false //所用的模型是否是上传的模型
const uploadRef = ref()

//用于提交到后端时把模型的ip地址和端口替换
const localModelUrl = computed(() => {
	return modelPath.value
	/*let localUrl = modelPath.value
	if (isUpload) {
		localUrl = replaceHttpLink(modelPath.value, '10.21.31.38', '32133')
	}
	return localUrl*/
})

function replaceHttpLink(url, newIp, newPort) {
	// 匹配IP地址和端口  
	const ipPortRegex = /(https?:\/\/)((\d{0,3}\.){3}\d{1,3}:?\d{1,5})/;
	// 使用正则表达式进行匹配并替换  
	const newUrl = url.replace(ipPortRegex, function (match) {
		// 替换IP地址和端口  
		const ip = newIp.replace(/\./g, '.');
		const port = newPort ? `:${newPort}` : '';
		return match.replace(/(\d{1,3}\.){3}\d{1,3}:?\d{1,5}/, `${ip}${port}`);
	});
	return newUrl;
}

async function handleSubmitMeshForm(formEl) {
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				//创建子任务
				let { appId, appModuleId } = meshForm
				addSubTask({
					appId: appId,
					appModuleId: appModuleId,
					taskName: meshForm.taskName
				}).then((res) => {
					meshForm.subTaskId = res.data
					if (meshForm.subTaskId) {
						meshForm.stpPath = localModelUrl.value
						fastCaeMesh(meshForm).then((res) => {
							console.log('fastCaeMesh', res)
							if (res.code == 0) {
								ElMessage({
									message: res.data,
									type: 'success',
								})
							}
						})
					} else {
						ElMessage({
							message: '子任务ID能不能为空',
							type: 'warning',
						})
					}
				})
			} else {
				console.log('error submit!', fields)
			}
		})
}

const onMountedSetting = ref(null)
let onMountedstpLoader = null
//模型展示
function showModel() {
	if (!modelPath.value) {
		return
	}
	onMountedSetting.value = new LoaderSettings('viewer', 'modelPreview')
	//onMountedSetting.value.callback.onGetModelNodes = onGetModelNodes
	//onMountedSetting.value.callback.onChangeNodeIsShowState = onChangeNodeIsShowState
	//onMountedSetting.value.callback.onMeshDbClick = scrollIntoView
	const modelUrl = modelPath.value
	modelLoading.value = true
	onMountedstpLoader = new StpLoader(modelUrl, onMountedSetting.value, () => { modelLoading.value = false })
	console.log('onMountedstpLoader', onMountedstpLoader)
}

//文件上传
function uploadRequest(e) {

var formData = new FormData();
//e.target.files 获取fileList对象里的上传的file对象添加到formData里面
formData.append("file", e.file);
let token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6InRlc3RlciIsInVzZXJJZCI6MTQyMzYxNjU0fQ.alyZgfFwavfZysfYwpYXuarY5ZtBFjsyAmTDfdHdu_A'
const headers = {
	'Content-Type': 'multipart/form-data',
	'authorization': token,
	'signature': token
}
console.log('baseUrl', baseUrl.value)
//alert(baseUrl )
axios.post(`${baseUrl.value}/twt/upload`, formData, { headers }
).then(response => {
	form.value.filePath = response.data.message
	console.log('上传成功', response.data);
}).catch(error => {
	console.error('上传失败', error);
});
}


//文件上传调用
function upload() {
	if ((window.chrome && window.chrome.webview) || (window.qt && window.sendObject)) {
		updateFile({}).then((res) => {
			console.log('上传成功', res)
			isUpload = true
			ElMessage({
				message: res.message,
				type: 'success',
			})
			modelPath.value = res.data.fileUrl
			modelLocalPath.value = res.data.path
			showModel()
		})
	}else{
		//浏览器端上传
		uploadRef.value.$el.querySelector('input').click()
	}
}


onMounted(() => {

	showModel()
})


</script>
<style lang="scss">
.meshGeneration {
	min-height: calc(100vh - 60px);
	background-color: #fff;
	box-sizing: border-box;
	padding: 27px;
	min-width: 1020px;
	/* max-width: 1200px; */
	margin: 0 auto;
	margin-left: 0;
	width: 100vw;

	.startbtn,
	.startbtn:active,
	.startbtn:focus {
		width: 120px;
		height: 40px;
		opacity: 1;
		font-size: 14px;
		border-radius: 5px;
		color: #fff;
		background: rgb(0, 84, 254);
	}

	.modelBox {
		height: 600px;
	}

	.checkAll {
		margin-right: 20px !important;
	}

	.uploadForm input {
		cursor: pointer !important;
	}

	.el-form-item {
		margin-top: 14px;
		margin-bottom: 14px !important;
		margin-right: 10px;
	}

	.el-tabs__content * {
		z-index: 10;
	}

	.el-scrollbar__bar,
	.el-scrollbar__bar.is-vertical>div,
	.el-scrollbar__bar.is-horizontal>div {
		display: none;
	}

	.el-table--border .el-table__inner-wrapper::after,
	.el-table--border::after,
	.el-table--border::before,
	.el-table__inner-wrapper::before {
		content: unset;
		position: static;
	}

	td:first-child>div {
		padding: 0;
	}

	td:first-child>div li {
		display: inline-flex;
		align-items: center;
		width: 100%;
		text-align: center;
		justify-content: center;
	}

	.el-form-item__label {
		line-height: 1.3 !important;
		display: inline-flex;
		align-items: center !important;
	}

	.el-tabs__content * {
		overflow: visible !important;
	}

	.el-tabs__content {
		width: 120%;
		overflow: visible !important;
	}

	.complete {
		width: 100px;
	}

	.el-dialog__close {
		display: inline-flex;
		width: 21px;
		align-items: center;
		justify-content: center;
		height: 21px;
		border-radius: 50%;
		background-color: #f56c6c;
		color: #fff !important;
	}

	.modelDisplay {
		height: calc(100% - 28px);
	}

	.tbTitle {
		font-size: 16px;
		color: rgba(40, 45, 48, 1);
	}

	.model {
		box-sizing: border-box;

		padding-right: 20px;
		padding-bottom: 20px;
		height: 646px;
	}

	.paramsRow>div {
		margin-right: 20px;
	}

	.w91 {
		width: 91%;
	}

	.w100 {
		width: 100%;
	}

	h5 {
		font-size: 16px;
		font-weight: 400;
	}

	.w63 {
		width: 63%;
	}

	.el-input {
		height: 40px;
	}

	.el-form-item__label {
		height: 40px;
		line-height: 40px;
		justify-content: flex-start;
	}

	.el-tabs__nav-wrap::after {
		visibility: hidden;
	}

	.el-tabs__item {
		padding: 0;
		width: 200px;
	}

	.modelBox {
		width: 726px;
		background-color: #8c8ca9;
		height: 451.89px;
	}

	.modelBox {
		width: 100%;
		background-color: #8c8ca9;
		height: 451.89px;
	}

	th {
		background-color: #f6f9fe !important;
	}
}
</style>